package com.ant.backstage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ant.backstage.dao.*;
import com.ant.backstage.facade.ApiReturn;
import com.ant.backstage.facade.code.ApiReturnCode;
import com.ant.backstage.facade.dto.*;
import com.ant.backstage.facade.enums.TagTypeEnum;
import com.ant.backstage.facade.enums.VerificationTypeEnum;
import com.ant.backstage.facade.exception.BackstageBusinessException;
import com.ant.backstage.facade.model.*;
import com.ant.backstage.facade.request.UpdateUserInfoRequest;
import com.ant.backstage.facade.request.power.UpdateUseRolesRequest;
import com.ant.backstage.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @date 2021/12/23 0:23
 **/
@Service("userService")
public class UserServiceImpl implements UserService {

    private static Logger logger = LogManager.getLogger(UserServiceImpl.class);

    @Resource
    UserMapper userMapper;
    @Resource
    RoleMapper roleMapper;
    @Resource
    UserroleMapper userroleMapper;
    @Resource
    RolepermissionMapper rolepermissionMapper;
    @Resource
    PermissionMapper permissionMapper;
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    TagMapper tagMapper;
    @Resource
    MapperFacade mapperFacade;

    @Override
    public User selectOneUser(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User selectUserByUid(String uid) {
        return userMapper.selectByUid(uid);
    }

    @Override
    public PageInfo selectPageUserInfo(User user, int pageNum, int pageSize) {
        //1. 根据条件筛选出符合条件的id
        List<String> uidList = userMapper.selectbyCondition(user);
        PageInfo<Object> pageInfo = null;
        List<User> resultList = null;
        if (!uidList.isEmpty()) {
            //使用pageHelper实现分页查询  注意设置完 pageHelper 以后需要接着查询
            PageHelper.startPage(pageNum, pageSize);
            resultList = userMapper.selectUserByuIds(uidList);
            pageInfo = new PageInfo(resultList);
        } else {
            logger.info("分页查询,没有符合条件的用户 user={}", JSONObject.toJSONString(user));
            return pageInfo;
        }
        List<Object> reutlslist = new ArrayList<>();
        //查用户的角色权限信息
        resultList.stream().forEach(item -> {
            Map<String, Object> itemMap = new HashMap<>();
            itemMap.put("user", item);
            //查角色
            List<Userrole> userRoles = userroleMapper.selectRoleByUid(item.getUid());
            List<Integer> roleIds = userRoles.stream().map(Userrole::getRoleId).collect(Collectors.toList());
            List<Role> roles = roleMapper.selectRoleByids(roleIds);
            logger.info("分页查询,组装用户角色信息 item={},userRoles={},roleIds={},roles={}",
                    JSONObject.toJSONString(item), JSONObject.toJSONString(userRoles)
                    , JSONObject.toJSONString(roleIds), JSONObject.toJSONString(roles));
            List<Object> rolesList = new ArrayList<>();
            roles.forEach(roleItem -> {
                PowerDTO powerDTO = new PowerDTO();
                powerDTO.setItemRole(roleItem);
                List<Rolepermission> rolepermissionList = rolepermissionMapper.selectByRoleId(roleItem.getId());
                List<Integer> permissionIds = rolepermissionList.stream().map(Rolepermission::getPermissionId).collect(Collectors.toList());
                List<Permission> permissionList = permissionMapper.selectByids(permissionIds);
                powerDTO.setPermissionList(permissionList);
                rolesList.add(powerDTO);
                logger.info("分页查询,组装用户角色&权限信息 roleItem={},rolepermissionList={},permissionIds={},permissionList={}",
                        JSONObject.toJSONString(roleItem), JSONObject.toJSONString(rolepermissionList)
                        , JSONObject.toJSONString(permissionIds), JSONObject.toJSONString(permissionList));
            });
            itemMap.put("power", rolesList);
            reutlslist.add(itemMap);
        });
        pageInfo.setList(reutlslist);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiReturn updateUserInfo(UpdateUserInfoRequest userRequest) {
        User user = new User();
        UserInfo userInfo = new UserInfo();
        ApiReturn apiReturn = new ApiReturn();

        //处理参数
        List<String> uphone = userRequest.getUphone();
        user.setUphone(uphone.get(0) +uphone.get(1))
                .setAge(userRequest.getAge()).setUid(userRequest.getUid());
        List<String> tagIds = new ArrayList<>();
        List<String> oldTagList = userRequest.getOldTagList();
        if (oldTagList != null) {
            tagIds.addAll(oldTagList);
        }
        List<String> newTagList = userRequest.getNewTagList();
        if (newTagList != null) {
            tagIds.addAll(newTagList);
        }

        String tagidsString = String.join(",", tagIds);

        userInfo.setPlaceNow(userRequest.getPlaceNow()).setPosition(userRequest.getPosition())
                .setMotto(userRequest.getMotto()).setMail(userRequest.getMail()).setAvatarImgUrl(userRequest.getAvatarImgUrl())
                .setUid(userRequest.getUid()).setTagid(tagidsString.trim());
        //修改用户信息
        userMapper.updateByUid(user);
        userInfoMapper.updateInfoByUid(userInfo);
        apiReturn.setApiReturnCode(ApiReturnCode.SUCCESSFUL);
        return apiReturn;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    //TODO 删除新增事务
    public ApiReturn updateUserRoles(List<String> split, UpdateUseRolesRequest roleAddRequest, ApiReturn apiReturn, UserDTO userPo) {
        //查修改人下所拥有的角色
        List<Userrole> userroles = userroleMapper.selectRoleByUid(userPo.getUid());
        List<Integer> collect = userroles.stream().distinct().map(Userrole::getRoleId).collect(Collectors.toList());
        //数组转集合
        List<String> splitList = split.stream().distinct().collect(Collectors.toList());
        //交集
        CollectionUtils.intersection(collect, splitList).stream().forEach(id -> {
            //2. 删除用户db中的角色[当前修改权限人下锁拥有的角色]，重新新增
            userroleMapper.delByuid(userPo.getUid(), String.valueOf(id));
        });
        CollectionUtils.intersection(collect, splitList).stream().forEach(id -> {
            Userrole userrole = new Userrole();
            userrole.setRoleId(Integer.valueOf((String) id));
            userrole.setUserUid(userPo.getUid());
            userroleMapper.insert(userrole);
        });
        apiReturn.setApiReturnCode(ApiReturnCode.SUCCESSFUL);
        return apiReturn;
    }

    @Override
    public ApiReturn updateUserStatus(String status, String uid) {
        ApiReturn apiReturn = new ApiReturn();
        userMapper.updateStatusByUid(status, uid);
        apiReturn.setApiReturnCode(ApiReturnCode.SUCCESSFUL);
        return apiReturn;
    }

    @Override
    public ApiReturn selectUserContact(String uname, String contactType) {
        ApiReturn apiReturn = new ApiReturn();
        User user = userMapper.selectbyName(uname);
        Map<String, Object> map = new HashMap<>();

        if (Optional.ofNullable(user).isPresent()) {
            VerificationTypeEnum byCode = VerificationTypeEnum.getByCode(contactType);
            if (byCode == null) {
                logger.error("枚举值异常 user={}", user);
                throw new BackstageBusinessException(ApiReturnCode.HTTP_ERROR.getMessage(), ApiReturnCode.HTTP_ERROR.getCode());
            }
            apiReturn.setApiReturnCode(ApiReturnCode.SUCCESSFUL);
            switch (byCode) {
                case VERIFICATION_MAIL:
                    UserInfo userInfo = userInfoMapper.selectbyUid(user.getUid());
                    if (!Optional.ofNullable(userInfo).isPresent() || !Optional.ofNullable(userInfo.getMail()).isPresent()) {
                        apiReturn.setCode(ApiReturnCode.NO_TERM_DATAS.getCode());
                        apiReturn.setMsg(ApiReturnCode.NO_TERM_DATAS.getMessage());
                        map.put("userContact", null);
                        apiReturn.setData(map);
                    } else {
                        map.put("userContact", userInfo.getMail());
                        apiReturn.setData(map);
                    }
                    break;
                case VERIFICATION_PHONE:
                    if (!Optional.ofNullable(user.getUphone()).isPresent()) {
                        apiReturn.setCode(ApiReturnCode.NO_TERM_DATAS.getCode());
                        apiReturn.setMsg(ApiReturnCode.NO_TERM_DATAS.getMessage());
                        map.put("userContact", null);
                        apiReturn.setData(map);
                    } else {
                        map.put("userContact", user.getUphone());
                        apiReturn.setData(map);
                    }
                    break;
            }
        }
        return apiReturn;
    }

    @Override
    public ApiReturn selectUserInfo(String uid) {
        ApiReturn apiReturn = new ApiReturn();
        User user = userMapper.selectByUid(uid);
        UserInfo userInfo = userInfoMapper.selectbyUid(uid);
        UserInfoDTO dto = mapperFacade.map(userInfo, UserInfoDTO.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dto.setAge(user.getAge()).setAddressid(user.getAddressid()).setCreatedatetime(sdf.format(user.getCreatedatetime()))
                .setGender(user.getGender()).setStatus(user.getStatus()).setUid(user.getUid()).setUname(user.getUname())
                .setUphone(user.getUphone());
        // 处理用户的标签 待实现  key label
        String tagid = userInfo.getTagid();
        if (StringUtils.isNotBlank(tagid)) {
            String[] split = tagid.split(",");
            List<String> tagsIds = Arrays.stream(split).distinct().collect(Collectors.toList());
            List<Tag> tagsList = tagMapper.selectTagsListByIds(tagsIds);
            List<TagLabelDTO> tagList = new ArrayList<>();
            tagsList.forEach(item->{
                TagLabelDTO tagLabelDTO = new TagLabelDTO();
                tagLabelDTO.setKey(String.valueOf(item.getId()));
                tagLabelDTO.setLabel(item.getTagName());
                tagList.add(tagLabelDTO);
            });
            dto.setTagList(tagList);
        }
        apiReturn.setApiReturnCode(ApiReturnCode.SUCCESSFUL);
        apiReturn.setData(dto);
        return apiReturn;
    }

    @Override
    public ApiReturn selectTagsByType(String type) {
        ApiReturn apiReturn = new ApiReturn();
        List<Tag> tags = tagMapper.selectTagsListByType(type);
        //不同类型，处理成不同参数
        if (type.equals(TagTypeEnum.USER_TYPE.getCode())) {
            List<TagValueDTO> dtos = new ArrayList<>();
            tags.forEach(ta->{
                TagValueDTO tagLabelDTO = new TagValueDTO();
                tagLabelDTO.setLabel(ta.getTagName());
                tagLabelDTO.setValue(String.valueOf(ta.getId()));
                dtos.add(tagLabelDTO);
            });
            apiReturn.setData(dtos);
        }
        apiReturn.setApiReturnCode(ApiReturnCode.SUCCESSFUL);
        return apiReturn;
    }

}
